	<link rel="stylesheet" type="text/css" href="resources/theme/cupertino/jquery-ui-1.9.0.custom.min.css"></link>
   	<script src="resources/js/jquery-ui-1.9.0.custom.min.js" type="text/javascript"> </script>
	<script src="resources/js/jquery-maskedinput-1.3.min.js" type="text/javascript"> </script>
	<script src="resources/js/jquery.maskMoney.js" type="text/javascript"> </script>

    <style>
    #customerName { width: 25em; }
    #address1 { width: 25em; }
    #address2 { width: 25em; }
    #ship_address1 { width: 25em; }
    #ship_address2 { width: 25em; }
    
    .fitem label{
		min-width:80px;
	}
    </style>
    
    <script>

    
    $(document).ready(function () {
   	 	$("#tel").mask("999-999-9999");
   	 	$("#fax").mask("999-999-9999");
   	 	$("#cell").mask("999-999-9999");
   	 	$("#zip").mask("99999");
   	 	$("#shipZip").mask("99999");
   	 	$("#paymentAmount").maskMoney({symbol:'$'});
   	 	$("#editOrderBtn").hide();
   	 	// if new order, ser State: NJ. If edit an order, then use the state in the order.
   	 	if("${order.state}"==""){
   	 		$('#state').combobox('setValue', "NJ");
   	 	}else{
   	    	$('#state').combobox('setValue', "${order.state}");
   	 	}
   	 	
   	 	if("${order.shipState}"==""){
   	 		$('#shipState').combobox('setValue', "NJ");
   	 	}else{
   	    	$('#shipState').combobox('setValue', "${order.shipState}");
   	 	}
   		  	   
   		$('input:radio[name="orderStatus"][value="${order.ordersStatus}"]').attr('checked',true);
   		$('input:radio[name="paymentMethod"][value="${order.initPaymentMethod}"]').attr('checked',true);
   		
   		if("${order.ordersStatus}"=="finished"){
   			$('#saveOrderBtn').hide();   			
   		}
   		
   	});
   
    
    
    $(function() {
 		
        function populateCustomerInfo( customer ) {
        	$("#address1").val(customer.address1);
            $("#address2").val(customer.address2);
            $("#tel").val(customer.tel);
            $("#fax").val(customer.fax);
            $("#email").val(customer.email);
            $("#city").val(customer.city);
            $('#state').combobox('setValue', customer.state);
            $("#zip").val(customer.zip);
            $("#contact").val(customer.contact);
            $("#cell").val(customer.cell);
            $("#customerId").val(customer.id);
            
        }

        
        $( "#customerName" ).autocomplete({
            source: function( request, response ) {
                $.ajax({
                    url: "getCustomerByName.json",
                    dataType: "json",
                    data: {
                        featureClass: "P",
                        style: "full",
                        maxRows: 30,
                        customerName: request.term
                    },
                    success: function( data ) {
                        response( $.map( data.customerList, function( item ) {                        	
                            return {
                                label: item.customerName,
                                value: item.customerName,
                                address1: item.address1,
                                address2:	item.address2,
                                tel: item.phone1,
                                fax: item.fax,
                                email: item.email,
                                city:item.city,
                                state:item.state,
                                zip:item.zip,
                                contact:item.contact,
                                cell:item.phone2,
                                id:item.id
                            }
                        }));
                    }
                });
            },
            
            minLength: 2,
            select: function( event, ui ) {
                // log( ui.item ?
                    // "Selected: " + ui.item.label + "|" +ui.item.address1 :
                    //  "Nothing selected, input was " + this.value);
    				
                // ui.item?$("#address1").val(ui.item.address1) : ("#address1").val("Please enter address.");
            	populateCustomerInfo(ui.item);
    				
	                
            },
            open: function() {
                $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
            },
            close: function() {
                $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
            }
        });
        
        function populateProductDesc(product) {
        	$("#desc").val(product.desc);        	
        }
        

        
        $( "#styleNo" ).autocomplete({
            source: function( request, response ) {
                $.ajax({
                    url: "getProductByStyleNo.json",
                    dataType: "json",
                    data: {
                        featureClass: "P",
                        style: "full",
                        maxRows: 30,
                        styleNo: request.term
                    },
                    success: function( data ) {
                        response( $.map( data.productList, function( product ) {                        	
                            return {
                            	label:	product.description,
                                value:	product.styleNo,
                            	desc:	product.description
                            }
                        }));
                    }
                });
            },
            
            minLength: 2,
            select: function( event, ui ) {
                // log( ui.product ?
                // "Selected: " + ui.item.label + "|" +ui.item.address1 :
                //  "Nothing selected, input was " + this.value);
    				
                // ui.item?$("#address1").val(ui.item.address1) : ("#address1").val("Please enter address.");
            	
                // alert("selected:" + ui.item );
                populateProductDesc(ui.item);    			
	                
            },
            open: function() {
                $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
            },
            close: function() {
                $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
            }
        });
        
        
        
    });   

    
    
    </script>

<form id="orderfm" name="orderfm" method="post" novalidate>

<input type="hidden" id="refreshIndicator" name="refreshIndicator"  value="${refresh}" >
<input type="hidden" id="orderId" name="orderId"  value="${order.orderId}"  >
<input type="hidden" id="datePurchased" name="datePurchased"  value="${order.datePurchased}" >
<input type="hidden" id="customerId" name="customerId"  value="${order.customerId}" >
<input type="hidden" id="hiddenEstPickupDate" name="hiddenEstPickupDate"  value="${order.estPickupDate}" >

<table style="width:100%; padding: 5px; border: 0px; border-style: solid;">
		<tr>
			<td>
				<div id="customerPanel" class="easyui-panel" title="Customer Information" iconCls="icon-user" collapsible=true
						style="margin-right:0px;" >  
				 	
					<table style="width:100%; padding: 5px; border: 0px; border-style:solid;">
						<tr><td colspan="2">
						<!-- <fieldset style="background-color: #EBEBEB; border-color: #CCCCCC;">  -->
							 <div class="fitem" style="padding-top: 10px; ">
							 	<table style="cellpadding: 0px; cellspacing: 0px; width:100%; border: 0px; border-style: solid;">
							 	<tr>
							 		<td style="padding-left:15px;" >
										<label style="padding-left:0px; width: 82px; padding-top: 3px; border: 0px; border-style: solid;border-color: #000000">NAME</label>
									    <input id="customerName" name="customerName" type="text" style="width: 334px;" class="easyui-validatebox"  required="required" value="${order.customerName}" />
							    	</td>
							    	<td>
							    		<label style="padding-left:20px; width: 43px; padding-top: 3px;">TEL</label>
									    <input id="tel" name="tel" type="text" size="12" maxlength="14" class="easyui-validatebox" required="required" value="${order.tel}" />
							    	</td>

							    	<td>
							    	<label style="padding-left:20px; width: 43px; padding-top: 3px;">EMAIL</label>
									    <input id="email" name="email"  type="text" size="34" maxlength="200" class="easyui-validatebox" required="required" value="${order.email}"/>
							    	</td>
							    	
							    	<td>
							    	<label style="padding-left:20px; width: 110px; padding-top: 3px;">EST. PICKUP DATE</label>
									        <input id="estPickupDate" name="estPickupDate" type="text" class="easyui-datebox" required="required" ></input>  
							    	</td>
							    </tr>
							    <tr>
							 		<td style="padding-left:15px;" >
							 		<label style="padding-left:0px; width: 82px; padding-top: 3px; border: 0px; border-style: solid;border-color: #000000" >CONTACT</label>
									    <input id="contact" name="contact" type="text" style="width: 334px;" required="required" value="${order.contact}" />
							    	</td>
							    	<td>
							    		<label style="padding-left:20px; width: 43px; padding-top: 3px;">FAX</label>
									    <input id="fax" name="fax" type="text" size="12" maxlength="14" value="${order.fax}" />
									</td>
							    	<td>
							    	<label style="padding-left:20px; width: 43px; padding-top: 3px;">CELL</label>
									    <input id="cell" name="cell" type="text" size="34" maxlength="14" value="${order.cell}" />
									</td>
									<td>
									</td>
							    </tr>
							    </table>							    
							</div>
						<!-- </fieldset>  -->
				 		</td>
				 		</tr>
					
						<tr>
							<td width="50%">
							<fieldset>
								<legend>Billing Address</legend>
								<div class="fitem">
								<table style="width:100%; border: 0px; border-style: solid; padding: 0px;">
									<tr>										
										<td style="width: 50px;"><label>Address</label></td>
										<td><input id="address1" name="address1" type="text" style="width: 338px;" class="easyui-validatebox" required="required" value="${order.address1}"/></td>
									</tr>
									
									<tr>	
										<td> </td>
										<td><input id="address2" name="address2" type="text" style="width: 338px;" value="${order.address2}" /></td>
									</tr>
									<tr>	
									<td><label>City/State/Zip</label> </td>
										<td>
											<input id="city" name="city" type="text" size="25" maxlength="200" required="required" value="${order.city}" />&nbsp;,&nbsp;&nbsp;
											<select id="state" name="state" class="easyui-combobox" style="width:51px;" >
													<option value="NJ">NJ</option>  
											        <option value="NY">NY</option> 
											        <option value="AK">AK</option>
													<option value="AL">AL</option>
													<option value="AR">AR</option>
													<option value="AZ">AZ</option>
													<option value="CA">CA</option>
													<option value="CO">CO</option>
													<option value="CT">CT</option>
													<option value="DC">DC</option>
													<option value="DE">DE</option>
													<option value="FL">FL</option>
													<option value="GA">GA</option>
													<option value="HI">HI</option>
													<option value="IA">IA</option>
													<option value="ID">ID</option>
													<option value="IL">IL</option>
													<option value="IN">IN</option>
													<option value="KS">KS</option>
													<option value="KY">KY</option>
													<option value="LA">LA</option>
													<option value="MA">MA</option>
													<option value="MD">MD</option>
													<option value="ME">ME</option>
													<option value="MI">MI</option>
													<option value="MN">MN</option>
													<option value="MO">MO</option>
													<option value="MS">MS</option>
													<option value="MT">MT</option>
													<option value="NC">NC</option>
													<option value="ND">ND</option>
													<option value="NE">NE</option>
													<option value="NH">NH</option>
													<option value="NM">NM</option>
													<option value="NV">NV</option>
													<option value="OH">OH</option>
													<option value="OK">OK</option>
													<option value="OR">OR</option>
													<option value="PA">PA</option>
													<option value="RI">RI</option>
													<option value="SC">SC</option>
													<option value="SD">SD</option>
													<option value="TN">TN</option>
													<option value="TX">TX</option>
													<option value="UT">UT</option>
													<option value="VA">VA</option>
													<option value="VT">VT</option>
													<option value="WA">WA</option>
													<option value="WI">WI</option>
													<option value="WV">WV</option>
													<option value="WY">WY</option> 
											    </select>
											<input id="zip" name="zip" type="text" size="10" maxlength="10" required="required" value="${order.zip}"/>
										
										</td>
									</tr>
								</table>
								</div>
							</fieldset>
							</td>
							<td width="50%">
								<fieldset>
									<legend>Shipping Address</legend>
									<div class="fitem">
								<table style="width:100%; padding: 0px; border:1px">
									<tr>										
										<td style="width: 50px;"><label>Address</label></td>
										<td><input id="shipAddress1" name="shipAddress1" type="text" style="width: 338px;" value="${order.shipAddress1}"/></td>
									</tr>
									
									<tr>	
										<td> </td>
										<td><input id="shipAddress2" name="shipAddress2" type="text" style="width: 338px;" value="${order.shipAddress2}"/></td>
									</tr>
									<tr>	
									<td><label>City/State/Zip</label> </td>
										<td>
											<input id="shipCity" name="shipCity" type="text" size="25" maxlength="200" value="${order.shipCity}"/>&nbsp;,&nbsp;&nbsp;
										    <select id="shipState" name="shipState" class="easyui-combobox" name="ship_state" style="width:51px;">
										    		<option value=""></option>
										    		<option value="NJ">NJ</option>  
											        <option value="NY">NY</option> 
											        <option value="AK">AK</option>
													<option value="AL">AL</option>
													<option value="AR">AR</option>
													<option value="AZ">AZ</option>
													<option value="CA">CA</option>
													<option value="CO">CO</option>
													<option value="CT">CT</option>
													<option value="DC">DC</option>
													<option value="DE">DE</option>
													<option value="FL">FL</option>
													<option value="GA">GA</option>
													<option value="HI">HI</option>
													<option value="IA">IA</option>
													<option value="ID">ID</option>
													<option value="IL">IL</option>
													<option value="IN">IN</option>
													<option value="KS">KS</option>
													<option value="KY">KY</option>
													<option value="LA">LA</option>
													<option value="MA">MA</option>
													<option value="MD">MD</option>
													<option value="ME">ME</option>
													<option value="MI">MI</option>
													<option value="MN">MN</option>
													<option value="MO">MO</option>
													<option value="MS">MS</option>
													<option value="MT">MT</option>
													<option value="NC">NC</option>
													<option value="ND">ND</option>
													<option value="NE">NE</option>
													<option value="NH">NH</option>
													<option value="NM">NM</option>
													<option value="NV">NV</option>
													<option value="OH">OH</option>
													<option value="OK">OK</option>
													<option value="OR">OR</option>
													<option value="PA">PA</option>
													<option value="RI">RI</option>
													<option value="SC">SC</option>
													<option value="SD">SD</option>
													<option value="TN">TN</option>
													<option value="TX">TX</option>
													<option value="UT">UT</option>
													<option value="VA">VA</option>
													<option value="VT">VT</option>
													<option value="WA">WA</option>
													<option value="WI">WI</option>
													<option value="WV">WV</option>
													<option value="WY">WY</option> 
											    </select>
											<input id="shipZip" name="shipZip" type="text" size="10" maxlength="10" value="${order.shipZip}"/>
										
										</td>
									</tr>
								</table>
								</div>
								</fieldset>
							</td>
						</tr>
					</table>

				</div>
			</td>
		</tr>
		
		<!-- start of order details -->
		<tr>
			<td>
				<div id="orderDetailPanel" class="easyui-panel" title="Order Details" iconCls="icon-tshirt" collapsible=true style="padding: 0px;height:200px" >
					<!-- <div style="padding: 10px; height:150px">  -->
						<table id="orderItemGrid" style="padding: 0px; height:600px"></table>
					<!-- </div>		 -->				
				</div>
			</td>
		</tr>
		
		<tr>
		<td>
			<table style="width:100%; padding: 0px; border-spacing:0px" >
			<tr>
			<td width="50%">
			<div id="otherInfoPanel" class="easyui-panel" title="Other Information" collapsible=false border=true style="padding-top: 10px;  height:150px;" >
						<label  style="padding-left: 10px; width: 100px; font-weight: bold; color: #686A6D; vertical-align:bottom;">Order Number:</label> ${order.orderId}
						<p>
						<label  style="padding-left: 10px; width: 100px; font-weight: bold; color: #686A6D; vertical-align:bottom;">Order Status:</label>
						<input type="radio" name="orderStatus" id="orderStatus" value="approved" style="vertical-align:bottom" class="required"> Approved Order
						<input type="radio" name="orderStatus" id="orderStatus" value="quotes" style="vertical-align:bottom" class="required"> Quote
						<p>
						<label  style="padding-left: 10px; width: 100px; font-weight: bold; color: #686A6D; vertical-align:middle;">Comment:</label>
						<input id="comment" name="comment"  type="text" size="80" maxlength="300" class="easyui-validatebox"  value="${order.comment}">
			</div>
			</td>
			
			<td width="50%" style="padding-right:6px; ">
			<div id="paymentPanel" class="easyui-panel" title="Payment Information" collapsible=false border=true style="padding-top: 10px;height:150px;margin-right:10px;" >
 			<div style="float: right; margin-right: 20px; vertical-align:middle;">
 			<table>
				<tr>
				   <td colspan="3" align="right">				
					<label  style="padding-left:0px; width: 100px; display:inline-block; border-style:solid;border-width:0px; font-weight: bold; color: #686A6D;">Total:</label>
					<td align="right" colspan="2" >				
						<div id="totalPrice" style="align: right; padding-right: 3px;" ></div>
					<td>
				</td>				
				</tr>
				<tr>
					<td>				
						<label  style="width: 100px; font-weight: bold; color: #686A6D; vertical-align:bottom;">Payment Type:</label>
					</td>
					<td>
						<input type="radio" name="paymentMethod" value="Cash" style="vertical-align:bottom" class="required"> Cash
						<input type="radio" name="paymentMethod" value="Check" style="vertical-align:bottom" class="required"> Check
						<input type="radio" name="paymentMethod" value="Credit" style="vertical-align:bottom" class="required"> Credit
					</td>
					<td>
						<label  style="padding-left:42px; width: 105px; padding-top: 0px; border-width: 1px; font-weight: bold; color: #686A6D; vertical-align:middle; ">Down Payment:</label>
					</td>
					<td>
						<a href="javascript:halfDown();" class="easyui-linkbutton" data-options="plain:true">(50%)</a>
					</td>
					<td>
						<input id="paymentAmount" name="paymentAmount" type="text" style="text-align: right; "size="10" maxlength="10" value="${order.totalPayment}" onblur="javascript:updateBalance(this.value)"/>
					</td>
				
				</tr>
				<tr>
				<td colspan="3" align="right">
				
						<label  style="padding-left:0px; width: 100px; display:inline-block; font-weight: bold; color: #686A6D;">Balance:</label>
				</td>
				<td align="right" colspan="2" >
						<div id="balance" style="align: right; padding-right: 3px;" ></div>
				</td>
				
 				
				</tr>
				</table>
				</div>
			</div>
			</td>
			</tr>
			</table>
			</td>
		</tr>
		
</table>


</form>
 <!-- 
		<div class="ui-widget" style="margin-top: 2em; font-family: Arial;">
		    <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
		</div>
 -->
 
 
 <div id="orderdetailtoolbar">
	<table cellpadding="5" cellspacing="0" style="width:100%;" >  
        <tr>  
            <td>  
				<a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newOrderItem()">New</a>
				<a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editOrderItem('#orderItemGrid')">Edit</a>
				<a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="removeOrderItem('#orderItemGrid')">Remove</a>				
			</td>
		 </tr>
	</table>	
</div>

<div id="order-buttons" style="padding:10px 10px 10px 0px">
	<a href="#" id="saveOrderBtn" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveOrder()">Save Order</a>
	<a href="orderlist" id="cancelOrderBtn" class="easyui-linkbutton" iconCls="icon-cancel" onclick="">Cancel</a>
	<span style="align: right;"><a href="#" id="editOrderBtn" class="easyui-linkbutton" iconCls="icon-edit" onclick="editOrder()">Edit Order</a></span>
</div>
 
 <div id="orderItemEditor" class="easyui-dialog" style="width:550px;height:300px; padding:0px 20px 0px 20px" closed="true" buttons="#dlg-buttons">
	<!-- <div class="ftitle">New Item</div>   -->
	
	<form id="orderitemform" name="orderitemform" method="post" novalidate>
		<!--
		 <div class="fitem">
			<input name="lineNo" id="lineNo" value="0" data-options="min:0,max:9999,editable:false" />
		</div>
		 -->
		 
		 <input type="hidden" id="fmurl" >
		<div class="fitem">
			<label>Style No.</label>
			<input id="styleNo" name="styleNo" type="text" style="width:150px;" class="easyui-validatebox" required="required"/>				
		</div>		

		<div class="fitem">
			<label>Description</label>
			<input id="desc" name="desc" type="text" style="width:300px;" maxlength="255" class="easyui-validatebox" required="required" />	
		</div>
		
		<div class="fitem">
			<label>Color</label>
			<input id="color" name="color" type="text" class="easyui-validatebox" style="width:150px;" required="required" />				
		</div>	
		
		<div class="fitem">
			<label>Size</label>
			<select id="size" name="size" class="easyui-combobox"  style="width:154px;" data-options="required:true">  
			    <option value="YS">YS</option>  
			    <option value="YM">YM</option>  
			    <option value="YL">YL</option>
			    <option value="S">S</option>
			    <option value="M">M</option>
			    <option value="L">L</option>
			    <option value="XL">XL</option>
			    <option value="2XL">2XL</option>
			    <option value="3XL">3XL</option>
			    <option value="4XL">4XL</option>
			    <option value="5XL">5XL</option>
			    <option value="6XL">6XL</option>			     
			</select> 
		</div>
				
		<div class="fitem">
			<label>Quantity</label>
			<input id="qty" name="qty" class="easyui-numberspinner" style="width:150px;"  class="easyui-validatebox" required="required" data-options="min:1,max:9999,editable:true"/>				
		</div>
		
		<div class="fitem">
        <label>Art Desc.</label>
        <input id="artDesc" name="artDesc" type="text" style="width:300px;" maxlength="255"/>  
    	</div>
    	<div class="fitemmsg" id="artDescMsg"></div>
		
		<div class="fitem">
        <label>Unit Price $</label>
        <input id="unitPrice" name="unitPrice" type="text" style="width:300px;" maxlength="20" class="easyui-numberbox" required="required" data-options="min:0,precision:2"/>  
    	</div>
    	<div class="fitemmsg" id="unitPriceMsg"></div>
    	
	</form>
</div>

<div id="dlg-buttons" style="padding:10px 10px 10px 0px">
	<a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveOrderItem('')">Save</a>
	<a id="saveAndMoreBtn" href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveOrderItem('more')">Save & More</a> <!-- save the current item and add more same items -->
	<a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#orderItemEditor').dialog('close')">Cancel</a>
</div>
 
 <script type="text/javascript">
 		
 		var currentOrderDetailPanelHeight = 200;
 		

 		
		$(document).ready(function () {
			
			$('#orderItemGrid').datagrid({  
			    url:'getOrderItemsInSession.json',
			    queryParams: {
					orderId: '',
					refresh: $('#refreshIndicator').val()					
				},
			    rownumbers: true,
			    fitColumns: true,
			    nowrap: false,
			    remoteSort: false,
			    striped: true,
			    singleSelect: true,
			    toolbar: '#orderdetailtoolbar',
			columns:[[					
			        {title:'Style No.',field:'styleNo',align:'left',width:50, sortable:true}, 
			        {title:'Product Description',field:'desc',align:'left', width:200}, 
			        {title:'Art Description',field:'artDesc',align:'center',width:200},
			        {title:'Color',field:'color',align:'center', width:60, sortable:true},
			        {title:'Size',field:'size',align:'center', width:30, sortable:true},			        
			        {title:'Qty',field:'qty',align:'center',width:30},			        
			        {title:'Unit Price',field:'unitPrice',align:'right',width:50,
			        	formatter: function(value,row,index){
							return formatCurrency(value);
						}			        
			        },
			        {title:'SubTotal',field:'subTotal',align:'right',width:50,
			        	formatter: function(value,row,index){
							return formatCurrency(value);
						}		
			        },
			    ]],//end of columns
			    
			    onDblClickRow: function(rowIndex, rowData){
			    	// alert('double clicked. ' + rowIndex);
			    	if (rowData){
						$('#orderItemEditor').dialog('open').dialog('setTitle','Edit Item');
						$('#orderitemform').form('load',rowData);				
						$('#fmurl').val('editOrderItem.json?lineNo='+rowIndex);
						$('#saveAndMoreBtn').linkbutton('disable');
					}
					//$(this).datagrid('beginEdit', index);
					//var ed = $(this).datagrid('getEditor', {index:index,field:field});
					//$(ed.target).focus();
				},
				
				onLoadSuccess:function(result){
					//if editing the order, then cannot change payment field
					if($('#orderId').val()!=''){					 
					 $('#paymentAmount').attr("disabled", "disabled");
					 // alert("--- " + $('#hiddenEstPickupDate').val());
					
					 //set the estPickupDate value
					 $('#estPickupDate').datebox('setValue', $.format.date(new Date($('#hiddenEstPickupDate').val()), "MM/dd/yyyy"));	
					 $('#datePurchased').val($.format.date(new Date($('#datePurchased').val()), "MM/dd/yyyy"));
					}
					
					updateTotalAndBalance(parseFloat(result.totalPrice));
				}
			    
			});
			
			
			$('#size').combobox({
				onSelect: function(){
					$('#color').focus();
				}
			});
		});
		
		//when user click on refresh button, the following programs give user a chance to save previous entered items
		$(window).on('load', function(){
			var currentRows = $('#orderItemGrid').datagrid('getRows');
				// alert(currentRows.length);
				if(currentRows!=null){
		        	// alert(rows.length);
		            if(currentRows.length > 0){
		            	$.messager.confirm('Confirm','<b>Previous order has NOT finished. Are you sure you want to start a NEW ORDER?</b><br><br>',function(r){  
				            if (r){  
				                $.post('clearOrderItems.json', function(result){  
				                    if (result.success){
				                    	// $('#orderItemGrid').datagrid('reload');
						               	//alert('success clean the session');
						               	$('#orderfm').form('clear');
						               	location.reload();
				                    } else {		                    	
				                        $.messager.alert({   // show error message  
				                            title: 'Error',		                            
				                            width: 400,
				                            height: 200,
				                            html: result.msg
				                            // msg: result.msg  
				                        });  
				                    }  
				                },'json');  
				            }  
				        });  
		            }
		        } 
			
		});
		
		
		function newOrderItem(){
			$('#orderItemEditor').dialog('open').dialog('setTitle','Add a New Item');
			$('#orderitemform').form('clear');
			$('#styleNo').focus();
			$('#saveAndMoreBtn').linkbutton('enable');
			
			// alert($('#todo_screen').tabs('getSelected').prop('title'));			
			// $('#owner').combobox('select', owner);
			// $('#dueDateMsg').html('');
			// $('#priorityMsg').html('');
			// $('#ownerMsg').html('');
			// $('#descMsg').html('');
			// url = 'saveToDo.json';
			$('#fmurl').val('saveOrderItem.json');
		}
		
		function saveOrderItem(moreAction){  
		    $('#orderitemform').form('submit',{  
		        // url: 'saveOrderItemInSession.json',
		        url: $('#fmurl').val(),
		        onSubmit: function(){
		            return $(this).form('validate');  		            
		        },  
		        success: function(result){
		        	// alert(result);
		            var result = eval('('+result+')');  
		            // alert(result);
		            if (result.success){ 
		            	
		            	if(moreAction=='more'){
		            		$('#size').combobox('clear');
		            		$('#qty').val('');
		            		//$('#color').val('');
		            	}else{
		                	$('#orderItemEditor').dialog('close');      // close the dialog  
		            	}
		                
		                $('#orderItemGrid').datagrid('reload');		                		               
		                
		                // every 5 lines of new items, adding 100px to the #orderDetailPanel height
		                var rows = $('#orderItemGrid').datagrid('getRows');
		                if(rows!=null && $('#fmurl').val().indexOf('saveOrderItem.json') == 0){
		                	// if((rows.length + 1)%5==0){
		                	if ((rows.length + 1) >= 5){
			                	// currentOrderDetailPanelHeight = currentOrderDetailPanelHeight +129;
			                	currentOrderDetailPanelHeight = currentOrderDetailPanelHeight +20;
			                	$('#orderDetailPanel').height(currentOrderDetailPanelHeight+'px');
			                	// $('#orderItemGrid').datagrid('resize');
			                	// $('#orderItemGrid').height(currentOrderItemGridHeight+'px');
			                	
			                }
		                }
		                //end of add height to the #orderDetailPanel
		                var displayMsg;
	                	if($('#fmurl').val().indexOf('editOrderItem.json') == 0){
	                		displayMsg =  'Item has been changed successfully.';
	                	}else if ($('#fmurl').val().indexOf('saveOrderItem.json') == 0){
	                		displayMsg =  'Item has been added successfully.';
	                	}
		                
					/*  $.messager.show({ 
		                    title: 'Result',		                    
		                    msg: displayMsg  
		                }); */  
		            } else {
		            	// $('#dueDateMsg').html(result.dueDateMsg);
		            	/* $('#priorityMsg').html(result.priorityMsg);
		            	$('#ownerMsg').html(result.ownerMsg);
		            	$('#descMsg').html(result.descMsg); */  
		                
		            	$.messager.show({  
		                    title: 'Error',
		                    width: 400,
                            height: 200,
                            timeout: 15000,
		                    msg: result.msg,
		                    style:{
		                        right:'',
		                        top:document.body.scrollTop+document.documentElement.scrollTop,
		                        bottom:''
		                    }
		                }); 
		            }  
		        }  
		    });  
		}  
		
		function removeOrderItem(dataGridName){
						
		    var row = $('#orderItemGrid').datagrid('getSelected');
		    var rowIndex = $("#orderItemGrid").datagrid("getRowIndex", row);
		    
		    if (row){  
		    			// alert('in removeToDo. RowIndex is:' + rowIndex);
		               $.post('removeOrderItem.json?lineNo='+rowIndex,{styleNo:row.styleNo, desc:row.desc, artDesc:row.artDesc, color:row.color, size:row.size, qty:row.qty, unitPrice:row.unitPrice, subTotal:row.subTotal},function(result){  
		                    if (result.success){  
				                //reload the dataGrid
		                    	$(dataGridName).datagrid('reload');

				                $.messager.show({
				                	title: 'Result',
				                	msg: 'Item has been removed successfully.',
				                    style:{
				                        right:'',
				                        top:document.body.scrollTop+document.documentElement.scrollTop,
				                        bottom:''
				                    }
				                }); 
		                    } else {		                    	
		                        $.messager.alert({   // show error message  
		                            title: 'Error',		                            
		                            width: 400,
		                            height: 200,
		                            html: result.msg
		                            // msg: result.msg  
		                        });  
		                    }  
		                },'json');		          
		    }else{
		    	$.messager.alert('Alert','Please select the item to be removed.');
		    	return false;
		    } 
			
		}
		
		
		function updateTotalAndBalance(totalPrice){
			
            var downPayment = Number($('#paymentAmount').val().replace(/[^0-9\.]+/g,""));
            // var totalPriceNum = Number(totalPrice.replace(/[^0-9\.]+/g,""));
            $('#totalPrice').html(formatCurrency(totalPrice));
            $('#balance').html(formatCurrency(totalPrice - downPayment));
            $('#paymentAmount').val(formatCurrency(downPayment));
		
		}
		
		function editOrderItem(dataGridName){
			var row = $(dataGridName).datagrid('getSelected');
			var rowIndex = $(dataGridName).datagrid("getRowIndex", row);
			// alert("size: " + row.size);
			if (row){
				$('#orderItemEditor').dialog('open').dialog('setTitle','Edit Item');
				$('#orderitemform').form('load',row);				
				// url = 'updateToDo.json';
				$('#fmurl').val('editOrderItem.json?lineNo='+rowIndex);
				// alert('disable the save and more button');
				$('#saveAndMoreBtn').linkbutton('disable');
			}else{
				$.messager.alert('Alert','Please select the item to be edited.');
		    	return false;
			}
		}
		
		
/* 		$(window).on('beforeunload', function(){
        	$.messager.show({  
                title: 'reload',
                width: 400,
                height: 200,
                timeout: 15000,
                msg: 'reloading'
            }); 
		}); */
		
		function saveOrder(){  
		    if(!$('input[name="orderStatus"]:checked').length){
		    	// alert ('Please select Order Status');
		    	$.messager.alert('Warning','<b>Please select Order Status.</b> <br>Approved Order or Quote?');
		    	return false;
		    }
			if ($('input[name="orderStatus"]:checked').val()=='quotes' || $('input[name="paymentMethod"]:checked').length ){
				$('#orderfm').form('submit',{  
			        url: 'saveOrder.json',
			        onSubmit: function(){
			        	
			        	// alert(document.getElementById('datePurchased').value());
			            return $(this).form('validate');  		            
			        },  
			        success: function(result){
			        	// alert(result);
			            var result = eval('('+result+')');  
			            // alert(result);
			            if (result.success){ 
		            		// alert(result.orderId);
		            		$('#orderId').val(result.orderId);		            		
		            		$('#datePurchased').val(result.purchaseDate);
		            		//disable all form items after order is save
		            		$('#orderfm').find(':enabled').each(function() {
		            		        $(this).attr("disabled", "disabled");
		            		});
		            		//disable Save Order button
		            		$('#saveOrderBtn').hide();
		            		$('#cancelOrderBtn').hide();
		            		$('#orderdetailtoolbar').hide();
		            		$('#editOrderBtn').show();
		            		
			                $.messager.show({ 
			                    title: 'Result',
			                    width: 400,
	                            height: 200,
			                    msg: "Order has been saved.",
			                    style:{
			                        right:'',
			                        top:document.body.scrollTop+document.documentElement.scrollTop,
			                        bottom:''
			                    }
			                });  
			            } else {
			            	// $('#dueDateMsg').html(result.dueDateMsg);
			            	/* $('#priorityMsg').html(result.priorityMsg);
			            	$('#ownerMsg').html(result.ownerMsg);
			            	$('#descMsg').html(result.descMsg); */  
			                
			            	$.messager.show({  
			                    title: 'Error',
			                    width: 400,
	                            height: 200,
	                            timeout: 15000,
			                    msg: result.msg,
			                    style:{
			                        right:'',
			                        top:document.body.scrollTop+document.documentElement.scrollTop,
			                        bottom:''
			                    }
			                }); 
			            }  
			        }  
			    });  
			}else{
				// alert (" Please select Payment Method.");
				$.messager.alert('Warning','<b>Please select Payment Method.</b>');
				return false;
			}
			
		    
		} 
		
		
		
		function updateBalance(downPayment){
			$('#orderItemGrid').datagrid('reload'); //when datagrid reload, it update the Balance
		}
		
		function halfDown(){
			//only entering the new order halfDown button is useful
			if($('#orderId').val()==''){
				var total = Number($('#totalPrice').html().replace(/[^0-9\.]+/g,""));
				// alert(total);
				$('#paymentAmount').val(formatCurrency(total/2));
				$('#orderItemGrid').datagrid('reload');
			}else{
				$.messager.alert('Warning','<p>Initial down payment cannot be changed from here. <P>You can go to Order List, then select Receive Payment function to enter additional payment.');
				
			}
			// alert(total);
		}
		
		function editOrder(){
    		$('#orderfm').find(':disabled').each(function() {
		        $(this).removeAttr("disabled");
			});
			//disable Save Order button
			$('#saveOrderBtn').show();
			$('#orderdetailtoolbar').show();
			$('#editOrderBtn').hide();
		
		}

</script>




	
 
	
	
	

















